#include "stdafx.h"
#include "AdvancedGraphicsViewer.h"
#include "bvh.h"

BVHNode* BVH::split( vector<Model*>& ms,  BVHTriangle* triangles, int num_triangles) {

		if (num_triangles == 0) return NULL;


		BVHNode* new_node = new BVHNode();
		new_node->bounding_box = calculateAABB( ms, triangles, num_triangles );
		new_node->num_triangles = num_triangles;
		if (num_triangles < 5) {
			new_node->triangles = triangles;
			
			new_node->left = NULL;
			new_node->right = NULL;
			return new_node;
		}

		float best_length = FLT_MIN;
		for (int i=0; i<3; i++) {
			if ( new_node->bounding_box.max_corner[i] - new_node->bounding_box.min_corner[i] > best_length) {
				axis_compare = i;
			}
		}

		unsigned int half_size = num_triangles / 2;
		std::nth_element (triangles, triangles+half_size, triangles + num_triangles);

		new_node->left = split( ms, triangles, half_size);
		new_node->right = split( ms, triangles + half_size, num_triangles - half_size);
		return new_node;
	} 